//
//  GJGCDTimer.m
//  yuanduo_app
//
//  Created by ZekiMini on 2021/8/3.
//

#import "GJGCDTimer.h"

@implementation GJGCDTimer
//存放定时器的全局字典
static NSMutableDictionary *timers;
// 信号量加锁
dispatch_semaphore_t semaphore;

+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        semaphore = dispatch_semaphore_create(1);
        timers = [NSMutableDictionary dictionary];
    });
}

+ (NSString *)execTask:(void (^)(void))task
                 start:(NSTimeInterval)start
              interval:(NSTimeInterval)interval
               repeats:(BOOL)repeats
                 async:(BOOL)async
{
    
    if (!task || interval<=0 || start<0) return nil;
    
    static int i = 0;
    
    // 定时器唯一标识符
    NSString *identify = [NSString stringWithFormat:@"timer%d",i++];
        
    // 队列
    dispatch_queue_t queue = async ? dispatch_get_global_queue(0, 0) : dispatch_get_main_queue();
    
    // 创建定时器
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    // 设置时间
    dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC), interval * NSEC_PER_SEC, 0);
    
    // 设置回调
    dispatch_source_set_event_handler(timer,^{
        
        task();
        if (!repeats) {
            [self cancelTask:identify];
        }
    });
    
    // 启动定时器
    dispatch_resume(timer);
    
    // 加锁
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    // 存放到全局字典
    timers[identify] = timer;
    // 解锁
    dispatch_semaphore_signal(semaphore);

    return identify;
}

+ (void)cancelTask:(NSString *)name
{
    if (name.length > 0 && timers.count > 0) {
        // 加锁
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_source_cancel(timers[name]);
        // 移除对应的timer
      
//        [timers removeObjectForKey:name];

        // 解锁
        dispatch_semaphore_signal(semaphore);
    }

}

+ (void)pauseTask:(NSString *)name{
  if (name.length > 0&& timers.count > 0) {
    dispatch_suspend(timers[name]);
  }
}

+ (void)resumeTimer:(NSString *)name{
  if (name.length > 0&& timers.count > 0) {
    dispatch_resume(timers[name]);
  }
}


@end
